package com.reny.ll.git.base_logic.api

import com.orhanobut.logger.Logger
import okhttp3.Interceptor
import okhttp3.Response
import okio.Buffer
import java.io.EOFException
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.nio.charset.UnsupportedCharsetException

class LoggerInterceptor : Interceptor {

    private val LOGGER_NET_TAG = "NET_TAG"

    override fun intercept(chain: Interceptor.Chain): Response {
        val orgRequest = chain.request()
        val response = chain.proceed(orgRequest)
        val body = orgRequest.body
        //val sb = StringBuilder()
        if (orgRequest.method == "POST") {
            var _body = ""
            if(null != body) {
                val buffer = Buffer()
                body.writeTo(buffer)

                var charset = StandardCharsets.UTF_8
                body.contentType()?.let {
                    charset = it.charset(StandardCharsets.UTF_8)
                }

                if (isPlaintext(buffer)) {
                    _body = buffer.readString(charset)
                }
            }
            //打印post请求的信息
            Logger.t(LOGGER_NET_TAG).d("code=" + response.code + "|method=" + orgRequest.method + "|url=" + orgRequest.url + "\nbody=$_body"
                    + "\n" + "headers:" + orgRequest.headers.toMultimap())
        } else {
            //打印get请求的信息
            Logger.t(LOGGER_NET_TAG).d("code=" + response.code + "|method=" + orgRequest.method + "|url=" + orgRequest.url
                    + "\n" + "headers:" + orgRequest.headers.toMultimap())
        }

        //返回json
        val responseBody = response.body
        val contentLength = responseBody!!.contentLength()
        val source = responseBody.source()
        source.request(java.lang.Long.MAX_VALUE)
        val buffer = source.buffer()
        var charset = Charset.defaultCharset()
        val contentType = responseBody.contentType()
        if (contentType != null) {
            try {
                charset = contentType.charset(charset)
            } catch (e: UnsupportedCharsetException) {
                return response
            }

        }
        if (contentLength != 0L) {
            Logger.t(LOGGER_NET_TAG).json(buffer.clone().readString(charset))
        }
        return response
    }


    private fun isPlaintext(buffer: Buffer): Boolean {
        return try {
            val prefix = Buffer()
            val byteCount = if (buffer.size < 64) buffer.size else 64
            buffer.copyTo(prefix, 0, byteCount)
            for (i in 0..15) {
                if (prefix.exhausted()) {
                    break
                }
                val codePoint = prefix.readUtf8CodePoint()
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(
                        codePoint
                    )
                ) {
                    return false
                }
            }
            true
        } catch (e: EOFException) {
            false // Truncated UTF-8 sequence.
        }
    }
}